package net.hvacapp.cmvrfforandroid.ui.fragment;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.ui.product.ProductDetailActivity;
import net.hvacapp.cmvrfforandroid.ui.product.ProductXlActivity;
import net.hvacapp.cmvrfforandroid.ui.product.model.ProductData;
import net.hvacapp.cmvrfforandroid.ui.product.model.ProductDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */

@EFragment(R.layout.fragment_product)
public class ProductFragment extends BaseFragment {

    @ViewById(R.id.lv_branch_company)
    PullToRefreshListView mProductLv;
    @ViewById(R.id.sv_branch)
    android.widget.SearchView mSearchView;

    private QuickAdapter<ProductData> mQuickAdapter;

    private boolean mIsSearch; //当前是否是搜索视图结果
    private String mSearchStr; //搜索字符串
    private List<ProductData> mProductType;

    private int begin;
    private int end;

    
    public ProductFragment() {

    }

    @AfterViews
    public void init(){
        mIsSearch = false;
        mProductType = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ProductData item = new ProductData();
            switch (i) {
                case 0:
                    item.setXh("室内机");
                    break;
                case 1:
                    item.setXh("室外机");
                    break;
                case 2:
                    item.setXh("轻型商用空调");
                    break;
                case 3:
                    item.setXh("全热交换器");
                    break;
                case 4:
                    item.setXh("空气能热水机");
                    break;

            }
            mProductType.add(item);
        }


        mSearchView.setIconifiedByDefault(true);
        mSearchView.setFocusable(true);
        mSearchView.setSubmitButtonEnabled(true);
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<ProductData>(getActivity(), R.layout.product_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, ProductData item) {
                    if (mIsSearch) {
                        helper.setText(R.id.tv_title, item.getXh());
                        if (StringUtils.isEmpty(item.getXl())) {
                            helper.setVisible(R.id.tv_desc1, false);
                        } else {
                            helper.setVisible(R.id.tv_desc1, true);
                            helper.setText(R.id.tv_desc1, "系列：" + item.getXl());
                        }

                        if (StringUtils.isEmpty(item.getXs())) {
                            helper.setVisible(R.id.tv_desc2, false);
                        } else {
                            helper.setVisible(R.id.tv_desc2, true);
                            helper.setText(R.id.tv_desc2, "型式：" + item.getXs());
                        }
                    }
                    else {
                        helper.setVisible(R.id.tv_desc1, false);
                        helper.setVisible(R.id.tv_desc2, false);
                        helper.setText(R.id.tv_title, item.getXh());
                    }
                }
            };
        }

        mProductLv.setAdapter(mQuickAdapter);
        mProductLv.setMode(PullToRefreshBase.Mode.DISABLED);

        initData();

        initListener();
    }

    private void initListener() {
        mSearchView.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchStr = query + "";
                mIsSearch = true;
                mProductLv.setMode(PullToRefreshBase.Mode.BOTH);
                refreshData();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                String def = newText;
                return false;
            }
        });

        mSearchView.setOnCloseListener(new android.widget.SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                mIsSearch = false;
                mProductLv.setMode(PullToRefreshBase.Mode.DISABLED);
                initData();
//                loadBranchCompanyData(0, -1);
                return false;
            }
        });
        mProductLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mIsSearch) {
                    ProductData data = (ProductData) parent.getItemAtPosition(position);
                    Intent intent = new Intent(getActivity(), AnnotationUtil.get(ProductDetailActivity.class));
                    intent.putExtra("tag", data.getTag());
                    intent.putExtra("guidId", data.getGuidId());
                    startActivity(intent);
                }
                else {
                    //跳转到系列列表页面
                    Intent intent = new Intent(getActivity(), AnnotationUtil.get(ProductXlActivity.class));

                    //用的刷新list控件，会让视图的第一行position为1
                    switch (position) {
                        case 1:
                            intent.putExtra("tag", ProjectInfoData.MACHINE_TAG_FOR_SNJ);
                            break;
                        case 2:
                            intent.putExtra("tag", ProjectInfoData.MACHINE_TAG_FOR_SWJ);
                            break;
                        case 3:
                            intent.putExtra("tag", ProjectInfoData.MACHINE_TAG_FOR_QXSYKT);
                            break;
                        case 4:
                            intent.putExtra("tag", ProjectInfoData.MACHINE_TAG_FOR_QRJHQ);
                            break;
                        case 5:
                            intent.putExtra("tag", ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ);
                            break;
                    }
                    startActivity(intent);
                }
            }
        });

        mProductLv.setOnRefreshListener(
                new PullToRefreshBase.OnRefreshListener<ListView>() {
                    @Override
                    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                        // 下拉刷新
                        if (refreshView.getCurrentMode().equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
                            // 下拉刷新
                            refreshData();
                        } else {
                            // 上拉加载更多
                            loadMoreData();
                        }
                    }
                }

        );
    }

    private void initData() {
        mQuickAdapter.clear();
        mQuickAdapter.addAll(mProductType);
    }

    private void refreshData() {
        begin = 0;
        end = Constant.PAGE_COUNT + begin - 1;
        searchProducts(begin, end, mSearchStr);
    }

    private void loadMoreData() {
        begin = mQuickAdapter.getCount();
        end = Constant.PAGE_COUNT + begin - 1;
        searchProducts(begin, end, mSearchStr);
    }
//    private void loadCache() {
//        CacheDao dao = new CacheDao(getActivity());
//
//        ProductDataResp obj = dao.getResponse(HttpConstant.HTTP_GET_ALL_PRODUCTS, AccountManager.getInstance().getToken(), ProductDataResp.class);
//        if (obj != null && obj.getGetAllProductsResult() != null
//                && obj.getGetAllProductsResult().size() > 0) {
//            // 更新列表
//            mQuickAdapter.clear();
//            mQuickAdapter.addAll(obj.getGetAllProductsResult());
//        }
//    }

//    private void loadProductData() {
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("icd", 0);
//
//        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_PRODUCTS,
//                AccountManager.getInstance().getToken(), params,
//                new HttpCallbackHandle<ProductDataResp>() {
//
//                    @Override
//                    public void onSuccess(ProductDataResp obj) {
//                        boolean needRefresh = true;
//                        //写入缓存
//                        CacheDao dao = new CacheDao(getActivity());
//                        needRefresh = dao.setResponse(HttpConstant.HTTP_GET_ALL_PRODUCTS, AccountManager.getInstance().getToken(), Constant.CACHE_EXPIRED_TIME, obj);
//                        // 更新列表
//                        if (needRefresh) {
//                            mQuickAdapter.clear();
//                            mQuickAdapter.addAll(obj.getGetAllProductsResult());
//                        }
//
//                    }
//
//                    @Override
//                    public void onFailure(String response) {
//
//                    }
//
//                });
//    }

    private void searchProducts(final int begin, int end, String searchText) {

        Map<String, Object> param = new HashMap<>();
        param.put("si", begin);
        param.put("ei", end);
        param.put("kw", searchText);
        param.put("icd", 0);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_SEARCH_PRODUCTS, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<ProductDataResp>() {
            @Override
            public void onSuccess(ProductDataResp obj) {
                // 成功
                if (begin == 0) {
                    //下拉刷新，需要清空数据
                    mQuickAdapter.clear();
                }
                mQuickAdapter.addAll(obj.getSearchResult());
                mProductLv.onRefreshComplete();

            }

            @Override
            public void onFailure(String response) {
                mProductLv.onRefreshComplete();
                showToast("数据加载失败");
            }

        });
    }

}
